<template>
    <el-card shadow="never" class="border-0">
        <!-- 搜索 -->
        <el-form :model="searchForm" label-width="80px" class="mb-3" size="small">
            <el-row :gutter="20">
                <el-col :span="5" :offset="0">
                    <el-form-item label="工单名称">
                        <el-input v-model="searchForm.orderName" placeholder="工单名称" clearable></el-input>
                    </el-form-item>
                </el-col>
                <el-col :span="5" :offset="0">
                    <el-form-item label="工单状态">
                        <el-select v-model="searchForm.orderStatus" placeholder="工单状态">
                            <el-option v-for="item in orderStatus" :key="item.code" :label="item.description"
                                :value="item.code" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="5">
                    <div class="flex items-center justify-end">
                        <el-button type="primary" @click="getData">搜索</el-button>
                        <el-button @click="resetSearchForm">重置</el-button>
                    </div>
                </el-col>
            </el-row>
        </el-form>

        <!-- 表格数据 
        @row-click 当某一行被点击时会触发该事件
        @selection-change 当选择项发生变化时会触发该事件
        @select 当用户手动勾选数据行的 Checkbox 时触发的事件
        -->
        <!-- 表格数据 -->
        <el-table 
            :data="tableData" 
            stripe 
            style="width: 100%"
            v-loading="tableDataLoading" 
            :border="true"
            @select = "handlerSelect"
            @row-click="handleSelectionChange"
            highlight-current-row 
            ref="multipleTableRef" 
            :row-key="row => row.id">
            <el-table-column v-if="props.showSelection" type="selection" :reserve-selection="true" align="center" width="55" />
            <el-table-column label="工单名称" align="center" prop="orderName" show-overflow-tooltip></el-table-column>
            <el-table-column label="工单发布人" align="center" prop="createUserName" show-overflow-tooltip></el-table-column>
            <el-table-column label="工单执行人" align="center" prop="engineerNames" show-overflow-tooltip></el-table-column>
            <el-table-column label="工单金额" align="center" prop="sum"></el-table-column>
            <el-table-column label="工单状态" align="center">
                <template #default="{ row }">
                    {{ formatOrderStatus(row.orderStatus) }}
                </template>
            </el-table-column>
            <el-table-column label="开始时间" align="center" prop="startTime"> </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endTime"> </el-table-column>
        </el-table>

        <!-- 分页组件 -->
        <div class="flex items-center justify-center mt-5">
            <el-pagination background layout="prev, pager ,next" :total="total" :current-page="currentPage"
                :page-size="limit" @current-change="getData" />
        </div>
    </el-card>
</template>

<script setup>
import { ref, onMounted, reactive, defineProps, nextTick } from 'vue'
const tableData = ref([]) // 列表数据
const currentPage = ref(1)
const total = ref(0)
const limit = ref(10)
const tableDataLoading = ref(false)
const selectCheckList = ref([])
const multipleTableRef = ref()
const orderStatus = ref([])
import { api_orders_list, api_project_constant } from "~/api/ordersApi"

// props
const props = defineProps({
    showSelection: false,
    //已选择的工单id
    selectedOrderId: null,
})

// 查询条件
const searchForm = reactive({
    orderName: "",
    orderStatus: null,
    page: currentPage.value,
    size: limit.value
})

//当用户手动勾选数据行的 Checkbox 时触发的事件
function handlerSelect(selection, val) {
    // console.log("handlerSelect val===>",JSON.stringify(val))
    selectCheckList.value = [val]
    //清空所有勾选
    multipleTableRef.value.clearSelection()
    //选中当前行
    multipleTableRef.value.toggleRowSelection(val, true);
    //触发对外方法
    getCheckedOrder()
}

//当选择项发生变化时会触发该事件
function handleSelectionChange(val) {
    // console.log("handleSelectionChange===>",JSON.stringify(val))
    selectCheckList.value = [val]
    //清空所有勾选
    multipleTableRef.value.clearSelection()
    //选中当前行
    multipleTableRef.value.toggleRowSelection(val, true);
    //触发对外方法
    getCheckedOrder()
}

// 触发回显
const toggleSelection = async (rows) => {
    await nextTick(() => {
        if (rows) {
            rows.forEach((row) => {
                //console.log("row===>",JSON.stringify(row))
                if (row.orderId == props.selectedOrderId) {
                    multipleTableRef.value.toggleRowSelection(row, true) // 默认勾选
                } else {
                    multipleTableRef.value.toggleRowSelection(row, false) // 不选中
                }
            })
        } else {
            multipleTableRef.value.clearSelection()
        }
    })
}


// 生命周期
onMounted(async () => {
    //获取订单状态
    await getProjectConstant()
    //加载表格数据
    await getData()
})

//获取订单状态
async function getProjectConstant() {
    api_project_constant().then(res => {
        orderStatus.value = res?.orderStatuses
    })
}

//获取列表数据
async function getData(p = null) {
    if (typeof p == "number") {
        currentPage.value = p
    }
    tableDataLoading.value = true
    searchForm.page = currentPage.value
    api_orders_list(searchForm)
    .then(res => {
        tableData.value = res.records
        total.value = res.total
        currentPage.value = res.current
        //触发勾选
        toggleSelection(tableData.value)
    })
    .finally(() => {
        tableDataLoading.value = false
    })
}

const formatOrderStatus = (state) => {
    return orderStatus.value?.find(x => x.code == state).description
}

// 重置搜索框
const resetSearchForm = () => {
    searchForm.orderName = ""
    searchForm.orderStatus = null
    getData(1)
}

// 对外暴露方法
const emit = defineEmits([
    'getCheckedOrder',
])

const getCheckedOrder = () => {
    const selectData = selectCheckList.value
    let returnParams = selectData.length == 1 ? selectData[0] : null
    emit("getCheckedOrder", returnParams)
}
</script>

<style>
.el-table__header-wrapper .el-checkbox {
    display: none
}
</style>
